package com.quasar.hpatient.module.home;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.home.HomeBean;
import com.quasar.hpatient.bean.home_medicine.MedicineTodayBean;
import com.quasar.hpatient.module.doctor_chat.DoctorChatActivity;
import com.quasar.hpatient.module.home_bloodpressure.BloodpressureActivity;
import com.quasar.hpatient.module.home_bloodsugar.BloodsugarActivity;
import com.quasar.hpatient.module.home_daily.HomeDailyActivity;
import com.quasar.hpatient.module.home_event.EventActivity;
import com.quasar.hpatient.module.home_health.HealthActivity;
import com.quasar.hpatient.module.home_heartrate.HeartrateActivity;
import com.quasar.hpatient.module.home_inspection.HomeInspectionActivity;
import com.quasar.hpatient.module.home_medicine.MedicineActivity;
import com.quasar.hpatient.module.home_medicine_today.MedicineTodayActivity;
import com.quasar.hpatient.module.home_temperature.TemperatureActivity;
import com.quasar.hpatient.module.home_urinevolume.UrinevolumeActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.chat.ChatService;
import lib.quasar.context.BaseApp;
import lib.quasar.db.manager.DBManager;
import lib.quasar.db.table.Chat;
import lib.quasar.db.table.Message;
import lib.quasar.recycler.BaseCommonMultAdapter;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.recycler.model.MultModel;
import lib.quasar.util.BaseUtil;
import lib.quasar.util.DimenUtil;
import lib.quasar.widget.image.ChatImageView;
import okhttp3.RequestBody;

/**
 * description: 首页
 * created by kalu on 2018/3/19 16:14
 */
public class HomePresenter implements BasePresenter {


    int warn_sign= 0;
    int status = 0;

    public boolean isFlushFlag() {
        return flushFlag;
    }

    public void setFlushFlag(boolean flushFlag) {
        this.flushFlag = flushFlag;
    }

    private boolean flushFlag = true;

    private final LinkedList<HomeBean> mDatas = new LinkedList<>();

    public List<MedicineTodayBean.ItemBean> getDoseMedicine() {
        return doseMedicine;
    }

    public void setDoseMedicine(List<MedicineTodayBean.ItemBean> doseMedicine) {
        this.doseMedicine = doseMedicine;
    }

    public HomeBean getHomeBean(int position){

        if (position<0 || position>=mDatas.size())
            return null;
        return mDatas.get(position);
    }

    List<MedicineTodayBean.ItemBean>  doseMedicine = null;
    private BroadcastReceiver reciveMessage;

    public boolean isDoseAll(){
        for (MedicineTodayBean.ItemBean bean:doseMedicine) {
            if (bean.getStatus() == 0)
                return false;

        }
        return true;
    }

    final void refreshMessage(HomeView view, RecyclerView recycler) {

        while (mDatas.getLast().getMultType() == MultModel.TYPE_3) {
            mDatas.removeLast();
        }

        final List<Message> messageList = DBManager.getInstance().getMessageList(getPatientId());
        if (null != messageList && !messageList.isEmpty()) {
            for (Message temp : messageList) {
                final HomeBean messageModel = new HomeBean();
                messageModel.setMessageIcon(temp.getMessage_icon());
                messageModel.setMessageName(temp.getMessage_name());
                messageModel.setMessageText(temp.getMessage_text());
                messageModel.setMessageId(temp.getMessage_id());
                messageModel.setMessageNumber(temp.getMessage_num());
                messageModel.setMultType(MultModel.TYPE_3);
                messageModel.setMessageTime(temp.getMessage_time());
                mDatas.addLast(messageModel);
            }
        }

        view.refreshList(recycler);
//        recycler.scrollToPosition(recycler.getAdapter().getItemCount() - 1);
    }

    void initMessageBroadcast(HomeView view, RecyclerView recycler) {

        reciveMessage = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                final Chat chat = (Chat) intent.getSerializableExtra(ChatService.MESSAGE_MODEL);
                if (null == chat)
                    return;

                final Long messageId = chat.isOwn(getPatientId()) ? chat.getReceiveid() : chat.getSendid();
                final Message message = DBManager.getInstance().getMessage(messageId);
                if (null == message) return;

                for (int i = mDatas.size() - 1; i >= 0; i--) {

                    final HomeBean temp = mDatas.get(i);
                    if (temp.getMultType() != MultModel.TYPE_3) continue;

                    if (messageId.equals(temp.getMessageId())) {
                        if (!BaseUtil.isForeground("com.quasar.hpatient.module.doctor_chat.DoctorChatActivity"))
                            temp.setMessageNumber(message.getMessage_num());
                        temp.setMessageText(message.getMessage_text());
                        temp.setMessageTime(message.getMessage_time());
                        view.refreshList(recycler);
                        return;
                    }
                }

                final HomeBean messageModel = new HomeBean();
                messageModel.setMessageIcon(message.getMessage_icon());
                messageModel.setMessageName(message.getMessage_name());
                messageModel.setMessageText(message.getMessage_text());
                messageModel.setMessageId(message.getMessage_id());
                messageModel.setMessageNumber(message.getMessage_num());
                messageModel.setMessageTime(message.getMessage_time());
                messageModel.setMultType(MultModel.TYPE_3);
                mDatas.addLast(messageModel);
            }
        };
        // 接收消息
        LocalBroadcastManager.getInstance(BaseApp.getContext()).registerReceiver(reciveMessage, new IntentFilter(ChatService.INTENT_NAME));
    }

    void initList(final HomeView view, RecyclerView recycler) {

        if (null == view || null == recycler) return;

        for (int i = 0; i < 4; i++) {
            HomeBean temp = new HomeBean();
            temp.setMultType(i == 1 ? MultModel.TYPE_1 : MultModel.TYPE_0);
            mDatas.addLast(temp);
        }

        final List<Message> messageList = DBManager.getInstance().getMessageList(getPatientId());
        if (null != messageList && !messageList.isEmpty()) {
            for (Message temp : messageList) {
                final HomeBean messageModel = new HomeBean();
                messageModel.setMessageIcon(temp.getMessage_icon());
                messageModel.setMessageName(temp.getMessage_name());
                messageModel.setMessageText(temp.getMessage_text());
                messageModel.setMessageId(temp.getMessage_id());
                messageModel.setMessageNumber(temp.getMessage_num());
                messageModel.setMessageTime(temp.getMessage_time());
                messageModel.setMultType(MultModel.TYPE_3);
                mDatas.addLast(messageModel);
            }
        }

        final BaseCommonMultAdapter<HomeBean> adapter = new BaseCommonMultAdapter<HomeBean>(mDatas) {
            @Override
            protected void onMult() {
                addMult(MultModel.TYPE_0, R.layout.fragment_home_type_class);
                addMult(MultModel.TYPE_1, R.layout.fragment_home_type_menu);
                addMult(MultModel.TYPE_2, R.layout.fragment_home_type_medicine);
                addMult(MultModel.TYPE_3, R.layout.fragment_home_type_message);
            }

            @Override
            protected void onNext(RecyclerHolder holder, HomeBean model, int position) {

                switch (model.getMultType()) {
                    case MultModel.TYPE_0:

                        holder.setOnClickListener(R.id.fragment_home_type_class_btn1, null);
                        holder.setOnClickListener(R.id.fragment_home_type_class_btn2, null);

                        if (position == 0) {
                            view.setText(holder, R.id.fragment_home_type_class_name, "我的健康");
                            view.setImage(holder, R.id.fragment_home_type_class_image, R.drawable.ic_my_friend);
                            view.setVisibility(holder, R.id.fragment_home_type_class_arrow, View.INVISIBLE);
                            view.setVisibility(holder, R.id.fragment_home_type_class_btn1, View.INVISIBLE);
                            view.setVisibility(holder, R.id.fragment_home_type_class_btn2, View.INVISIBLE);
                        } else if (position == 2) {
                            view.setText(holder, R.id.fragment_home_type_class_name, "服药提醒");
                            view.setText(holder, R.id.fragment_home_type_class_btn1, "一键服药");
                            view.setText(holder, R.id.fragment_home_type_class_btn2, "刷新");
                            view.setImage(holder, R.id.fragment_home_type_class_image, R.drawable.ic_my_prescription);
                            view.setVisibility(holder, R.id.fragment_home_type_class_arrow, View.VISIBLE);
                            view.setVisibility(holder, R.id.fragment_home_type_class_btn1, View.VISIBLE);
                            view.setVisibility(holder, R.id.fragment_home_type_class_btn2, View.VISIBLE);

                            holder.setOnClickListener(R.id.fragment_home_type_class_btn2, v -> medicineList(view, recycler, true));
                            holder.setOnClickListener(R.id.fragment_home_type_class_btn1, v -> view.showWarning());
                            holder.setOnClickListener(R.id.fragment_home_type_class_arrow, v -> view.goNext(MedicineTodayActivity.class));
                        } else {
                            view.setText(holder, R.id.fragment_home_type_class_name, "诊疗消息");
                            view.setText(holder, R.id.fragment_home_type_class_btn1, "复查消息");
                            view.setImage(holder, R.id.fragment_home_type_class_image, R.drawable.ic_my_message);
                            view.setVisibility(holder, R.id.fragment_home_type_class_arrow, View.VISIBLE);
                            view.setVisibility(holder, R.id.fragment_home_type_class_btn1, View.VISIBLE);
                            view.setVisibility(holder, R.id.fragment_home_type_class_btn2, View.INVISIBLE);
                        }
                        break;
                    case MultModel.TYPE_1:
                        holder.setOnClickListener(R.id.home_type_menu_temperature, v -> view.goNext(TemperatureActivity.class));
                        holder.setOnClickListener(R.id.home_type_menu_bloodpressure, v -> view.goNext(BloodpressureActivity.class));
                        holder.setOnClickListener(R.id.home_type_menu_bloodsugar, v -> view.goNext(BloodsugarActivity.class));
                        holder.setOnClickListener(R.id.home_type_menu_heartrate, v -> view.goNext(HeartrateActivity.class));
                        holder.setOnClickListener(R.id.home_type_menu_urinevolume, v -> view.goNext(UrinevolumeActivity.class));
                        holder.setOnClickListener(R.id.home_type_menu_daily, v -> view.goNext(HomeDailyActivity.class));
                        holder.setOnClickListener(R.id.home_type_menu_inspection, v -> view.goNext(HomeInspectionActivity.class));
                        holder.setOnClickListener(R.id.home_type_menu_medicine, v -> view.goNext(MedicineActivity.class));
                        holder.setOnClickListener(R.id.home_type_menu_history, v -> view.goNext(HealthActivity.class));
                        holder.setOnClickListener(R.id.home_type_menu_event, v -> view.goNext(EventActivity.class));
                        break;
                    case MultModel.TYPE_3:
                        final ChatImageView image = holder.getView(R.id.home_message_icon);
                        image.setBadgeNumber(model.getMessageNumber());
                        view.setImage(image, model.getMessageIcon(), true);
                        view.setText(holder, R.id.home_message_info, model.getMessageText());
                        view.setText(holder, R.id.home_message_name, model.getMessageName());
                        view.setText(holder, R.id.home_message_time, model.getMessageTime());
                        holder.setOnClickListener(R.id.fragment_home_recycler, v -> {
                            final int messageNumber = model.getMessageNumber();
                            view.minusBadgeNumber(messageNumber);
                            model.setMessageNumber(0);
                            image.setBadgeNumber(0);
                            DBManager.getInstance().clearMessage(model.getMessageId());
                            Intent intent = new Intent(holder.itemView.getContext(), DoctorChatActivity.class);
                            intent.putExtra(DoctorChatActivity.CHAT_ID, String.valueOf(model.getMessageId()));
                            intent.putExtra(DoctorChatActivity.CHAT_NAME, model.getMessageName());
                            view.goNext(intent);
                        });
                        break;
                    case MultModel.TYPE_2:
                        holder.setOnClickListener(null);
                        if (model.isMedicineNull()){
                            view.setText(holder, R.id.home_type_medicine_name, "药品");
                            view.setText(holder, R.id.home_type_medicine_num, "剂量");
                            view.setText(holder, R.id.home_type_medicine_unit,"规格");
                            view.setText(holder, R.id.home_type_medicine_time,"时间");
                            view.setText(holder, R.id.home_type_medicine_info,"状态");
                            view.setTextColor(holder, R.id.home_type_medicine_info, R.color.color_black);
                            break;
                        }

                        holder.setOnClickListener(R.id.home_type_medicine_info, v -> {
                            if (model.getMedicine().isMedicineOral()) {
                                view.toast(model.getMedicineName() + ": 已经服用过了");
                            } else {

                                view.showHint(position,getDoseStatus(model.getMedicine()));
                            }
                        });
                        view.setText(holder, R.id.home_type_medicine_name, model.getMedicine().getMname());
                        view.setText(holder, R.id.home_type_medicine_num, model.getMedicine().getMedicineNumbers());
                        view.setText(holder, R.id.home_type_medicine_unit, model.getMedicine().getDose_name());
                        view.setText(holder, R.id.home_type_medicine_time, model.getMedicine().getMedicineTime());
                        view.setText(holder, R.id.home_type_medicine_info, model.getMedicine().getMedicineInfo());
                        view.setTextColor(holder, R.id.home_type_medicine_info, model.getMedicine().getMedicineColors());


                        break;
                }
            }
        };

        final RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dp2px(180));
        final View head = LayoutInflater.from(BaseApp.getContext()).inflate(R.layout.fragment_home_type_head, null);
        head.setLayoutParams(params);
        adapter.addHead(head);

        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        view.setRecycler(recycler, adapter, manager);
    }

    final void medicineList(final HomeView view, RecyclerView recycler, boolean isRefresh) {


        if (!isFlushFlag())
            return;
        setFlushFlag(false);
        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.PRESCRIPTION_DATE, getDate());

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_5_4);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().medicineMessage(params);

        while (mDatas.get(3).getMultType() == MultModel.TYPE_2) {
            mDatas.remove(3);
        }

        request(observable, new OnModelAcceptChangeListener<MedicineTodayBean>() {
            @Override
            public void modelComplete() {
                super.modelComplete();
                setFlushFlag(true);
            }

            @Override
            public void modelFail() {
                super.modelFail();
                setFlushFlag(true);
            }

            @Override
            public void modelSucc(MedicineTodayBean result) {

                if (isRefresh) {
                    view.toast("刷新成功");
                }

                if (null == result)
                    return;
                warn_sign = result.getWarn_sign();
                status = result.getStatus();

                final List<MedicineTodayBean.ItemBean> list = result.getDatas();
                setDoseMedicine(result.getDatas());
                if (null == list || list.isEmpty())
                    return;

                for (int i = list.size() - 1; i >= 0; i--) {
                    if (list.get(i).getStatus() != 0)
                        continue;
                    final HomeBean medicineModel = new HomeBean();
                    final MedicineTodayBean.ItemBean temp = list.get(i);
//                    medicineModel.setMedicineName(temp.getMname());
//                    medicineModel.setMedicineOrder(temp.getUse_order());
//                    medicineModel.setMedicineNumber(temp.getUse_number());
//                    medicineModel.setMedicineUnit(temp.getDose_name());
//                    medicineModel.setMedicineTime(temp.getUse_time());
//                    medicineMode l.setMedicineDate(result.getPrescription_date());
//                    medicineModel.setMedicineTimeReal(temp.getReal_use_time());
//                    medicineModel.setMedicineStatus(temp.getStatus());
                    medicineModel.setMedicine(temp);
                    medicineModel.setMultType(MultModel.TYPE_2);
                    mDatas.add(3, medicineModel);
                    if (i != 0) continue;
                    final HomeBean nullModel = new HomeBean();
                    nullModel.setMultType(MultModel.TYPE_2);
                    mDatas.add(3, nullModel);
                }
                view.refreshList(recycler);
                setFlushFlag(true);
            }
        });
    }

    final void editMedicineOral(final HomeView view, RecyclerView recycler, int position,int flag) {

        if (!isFlushFlag())
            return;
        setFlushFlag(false);
        String prescriptionDate = getDate();
        final String usetime = getSecond();
        final LinkedList<MedicineTodayBean.ItemBean> list = new LinkedList();
        for (HomeBean temp : mDatas) {
            if (!temp.isMedicine() || temp.isMedicineNull()) continue;
            if (position == -1) {

                if (temp.getMedicine().isMedicineOral()) continue;


                temp.getMedicine().setStatus(flag);
                temp.getMedicine().setReal_use_time(usetime);

            } else {

                final int i = mDatas.indexOf(temp);
                if (i == position) {


                      final String medicineTimes = getMedicineDate(temp.getMedicine().getUse_time());
                      temp.getMedicine().setReal_use_time(usetime);

                      temp.getMedicine().setStatus(flag);
                    if (1 == flag){

                        if (getDoseStatus(temp.getMedicine()) == 0)
                            temp.getMedicine().setStatus(1);
                        else {
                            temp.getMedicine().setStatus(2);
                            warn_sign = 1;

                        }

                    }

                    mDatas.remove(position);
                    if (isDoseAll())
                        mDatas.remove(3);
                        status = 1;
                    break;


                }
            }
        }

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.DOSE_DATE, prescriptionDate);
        map.put(HttpParams.JSON_CONTENT, getDoseMedicine());
        map.put(HttpParams.WARN_SIGN, warn_sign);
        map.put(HttpParams.STATUS, status);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_5_5);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().uploadData(params);

        request(observable, new OnModelAcceptChangeListener<Object>() {
            @Override
            public void modelSucc(Object result) {

                if (position == -1) {
                    for (HomeBean temp : mDatas) {
                        if (!temp.isMedicine() || temp.isMedicineNull() || temp.isMedicineOral())
                            continue;
                        temp.setMedicineStatus(1);
                        temp.setMedicineTimeReal(usetime);
                    }
                }

                view.toast("操作成功");
                setFlushFlag(true);

            }

            @Override
            public void modelFail() {

                if (position != -1) {
                    final HomeBean model = mDatas.get(position);
                    model.setMedicineStatus(0);
                    model.setMedicineTimeReal("");
                }
                view.toast("操作失败");
                setFlushFlag(true);
            }

            @Override
            public void modelComplete() {
                view.refreshList(recycler);
                setFlushFlag(true);
            }
        });

        view.refreshList(recycler);

    }


    int getDoseStatus(MedicineTodayBean.ItemBean bean){
        final String usetime = getSecond();
        final String medicineTimes = getMedicineDate(bean.getUse_time());
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            final Date date1 = sdf.parse(medicineTimes);
            final Date date2 = sdf.parse(usetime);
            if ((date2.getTime()-date1.getTime()) > 1800000)
                return 1;
            if ((date1.getTime()-date2.getTime()) > 1800000)
                return -1;

        }catch (Exception e) {
            return 0;
        }

        return 0;
    }

    void bannerList(final HomeView view) {

        final ArrayList<String> list = new ArrayList<>();
        new android.os.Handler().postDelayed(() -> {
            list.add("http://img.zcool.cn/community/01223c5541fed80000019ae9a6633a.jpg@2o.jpg");
            list.add("http://img.zcool.cn/community/01223c5541fed80000019ae9a6633a.jpg@2o.jpg");
            list.add("http://img.zcool.cn/community/01223c5541fed80000019ae9a6633a.jpg@2o.jpg");
            view.setBanner(list);
        }, 1000);
    }

    @Override
    public void recycler() {

        if (null == reciveMessage) return;
        LocalBroadcastManager.getInstance(BaseApp.getContext()).unregisterReceiver(reciveMessage);
    }


}